package com.iwhalecloud.bss.kite.cucc.order.loader.impl;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.cucc.order.loader.IInstLoader;
import com.iwhalecloud.bss.kite.cucc.order.util.TableUtils;
import com.iwhalecloud.bss.kite.dataservice.entity.inst.IInst;
import com.iwhalecloud.bss.kite.dataservice.enums.TableConfig;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.order.client.dto.InstContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.base.extmapper.BaseMapper;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

/**
 * 实例加载器
 * @param <T>
 */
@Component("orderInstLoader")
public class InstLoader<T extends IInst> implements IInstLoader<T> {

    @Override
    public T loadInst(OrderRequest orderRequest, String tableName, String instId, String custId) {
        T inst = InstContainer.ofRequest(orderRequest).getInst(tableName, instId);
        if (Objects.isNull(inst)) {
            inst = getInst(tableName, instId, custId);
            InstContainer.ofRequest(orderRequest).addInst(inst);
        }
        return inst;
    }

    @Override
    public T getInst(String tableName, String instId, String custId) {
        TableConfig tableConfig = EnumUtils.getEnum(TableConfig.class, StringUtils.upperCase(tableName));
        if (Objects.isNull(tableConfig)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("no table config [TableConfig." + tableName + "]");
        }

        T inst = null;
        Class<? extends IInst> entityClass = tableConfig.getEntityClass();
        BaseMapper<T> baseMapper = TableUtils.getMapper(tableName, entityClass);
        if (StringUtils.isNotBlank(custId)) {
            Example example = new Example(entityClass);
            example.createCriteria().andEqualTo(tableConfig.getIdField(), instId)
                .andEqualTo(tableConfig.getSliceKeyField(), custId);
            inst = baseMapper.selectOneByExample(example);
        }
        if (Objects.isNull(inst)) {
            inst = baseMapper.selectByPrimaryKey(instId);
        }

        T newInst = KiteObjectUtils.clone(inst);
        if (Objects.nonNull(newInst) && Objects.equals(ActionType.A.name(), newInst.getActionType())) {
            newInst.setNewActionType(ActionType.K.name());
        }
        return newInst;
    }
}
